package org.xurui.sxl.protocol.command.impl;

import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.event.EventMessage;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 白名单主动获取
 */
public class CmdCodec_GETWLALL implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.GETWLALL.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return false;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //白名单主动获取 设备上报 TODO 没有 SV,BAT
        //格式：*XX,YYYYYYYYYYYYYYY,GETWLALL,HHMMSS,MCC,MNC,LAC,CELLID,DDMMYY,tracker_status#
        //例子：*TJ,2020916012,GETWLALL,130305,460,11,30538,218959638,220902,FFFFFFFF#
        //回复格式：*XX,YYYYYYYYYYYYYYY,WLALL,HHMMSS,wl-num,wl-phone,wl_type,…#
        //回复示例：*TJ,2020916012,WLALL,130306,1,13612345678,1,2,13612345678,1,3,13612345678,1,4,13612345678,1,5,13612345678,2,6,13612345678,2,7,13612345678,2,8,13612345678,2,9,13612345678,2,10,13612345678,2#
        //参数说明：WLALL 协议 4.3
        //参数说明：LBS MCC,MNC,LAC,CELLID 见基站信息格式
        //解析数据为事件上报
        EventMessage eventMessage = new EventMessage();
        //ReportPropertyMessage report = ReportPropertyMessage.create();
        String[] payloadArr = payload.replaceAll("\\*", "").split(",");
        String deviceId = payloadArr[1];
        eventMessage.setEvent(CommandEnum.GETWLALL.name());
        eventMessage.setDeviceId(deviceId);
        eventMessage.setMessageId(deviceId + "_" + payloadArr[3]);
        eventMessage.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        properties.put("uptime",payloadArr[3]);
        properties.put("mcc", payloadArr[4]);
        properties.put("mnc", payloadArr[5]);
        properties.put("lac",payloadArr[6]);
        properties.put("cellId",payloadArr[7]);;
        properties.put("upday",payloadArr[8]);
        String trackerStatusHex = payloadArr[9];

        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        //report.setProperties(properties);
        eventMessage.setData(properties);
        //回复设备数据
        //TODO 暂时没找到设备回复消息的方法
        //TODO 没有回复参数 wl-num,wl-phone,wl_type,...
        /*String day= BinaryUtils.getDateFormat();
        String reply="*"+payloadArr[0]+","+deviceId+",V4,"+CommandEnum.GETSMS.name()+","+payloadArr[3]+","+day;
        context.getSession()
            .send(EncodedMessage
                .simple(Unpooled.wrappedBuffer(reply.getBytes())))
            .subscribe();*/
       // return genDeviceMessage(report);
        return genDeviceMessage(eventMessage);
    }
}
